package com.server.controller;

import com.server.anno.Sensitivity;
import com.server.domain.Code;
import com.server.domain.Response;
import com.server.entity.User;
import com.server.service.UserService;
import com.server.utils.LogUtils;
import com.server.utils.JwtUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
public class AdminController {
    @Resource
    UserService userService;

    //登录
    @PostMapping("/login")
    public Response login(@RequestBody User user){
        LogUtils.INFO.info("登录中");
        User e = userService.login(user);

        //登录成功,生成令牌,下发令牌
        if (e != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("nickname", e.getNickname());
            claims.put("password", e.getPassword());

            String jwt = JwtUtils.createToken(claims); //jwt包含了当前登录的员工信息
            LogUtils.INFO.info("用户名: {}", user.getNickname());
            LogUtils.INFO.info("\n令牌是: {}", jwt);
            return new Response("登录成功！令牌如下，有效期十五天",jwt, Code.RESONSE_OK);
        }
        //登录失败, 返回错误信息
        return new Response("用户名或密码错误",null, Code.BUSINESS_PARAM_ERR);
    }

    @PostMapping("/saveOrUpdateUser")
    @Sensitivity
    public Response addDeviceInfo(@RequestBody User user) {
        user.setTime(new Date());
        user.setToken(null);
        user.setId(null);
        boolean is_insert = userService.saveOrUpdate(user);
        return new Response("要插入数据:"+user,is_insert, Code.RESONSE_OK);
    }
}
